var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var fs = require("fs");
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {

        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.get("/addcount",function (req,res) {

  // let obj =  fs.readdirSync("public/data.json");
  // console.log(obj);

    fs.readFile("./public/data.json",function (err,data) {


          let num = JSON.parse(data.toString()).count;
          num++;
          let contentstr="{ \"count\":"+num+"}";
          let obj = JSON.stringify(contentstr);
          fs.writeFile("./public/data.json",contentstr,function (err) {

              if(!err){

                  res.json(num);
              }
          });
    });


});


app.get("/getcount",function (req,res) {


    fs.readFile("./public/data.json",function (err,data) {


        if(!err){

            let num = JSON.parse(data.toString()).count;
            res.json(num);

        }
    });
});

app.listen(8077);
module.exports = app;
